<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue2实现一个响应式</title>
</head>
<body>
  <div>
    <input type="text">
    订阅试图-1：<span class="box-1">1111</span>
  </div>
  <div>
    <input type="text">
    订阅试图-2：<span class="box-2">2222</span>
  </div>
</body>
<script>
  // 创建一个订阅器
  let Dep = {
    clientList: {},
    // 添加订阅者
    listen: function(key, fn) {
      // if (!this.clientList[key]) {
      //   this.clientList[key] = []
      // }
      // this.clientList[key].push(fn)

      (this.clientList[key] || (this.clientList[key] = [])).push(fn)
    },
    // 推送方法
    trigger: function() {
    
      let key = Array.prototype.shift.call(arguments),
          fns = this.clientList[key]

      if (!fns || fns.listen == 0) {
        return
      }    

      for (let i = 0, fn; fn = fns[i++];) {
        fn.apply(this, arguments) 
      }
    }
  }

  /**
   * 数据劫持
   * data: 要劫持的数据
   * tag: 这个数据的标签
   * dataKey: 需要变更字段
   * selector: dom节点
   **/
  let dataHijack = function({ data, tag, dataKey, selector }) {
    let value = '',
        el = document.querySelector(selector)
    
    // 数据劫持
    Object.defineProperty(data, dataKey, {
      get: function() {
        console.log('get');
      },
      set: function(val) {
        console.log('set')
        value = val
        Dep.trigger(tag, val)
      }
    })    

    // 添加订阅者
    Dep.listen(tag, function(text) {
      el.innerHTML = text
    })
  }
</script>
<script>
  let dataObj = {}
  dataHijack({
    data: dataObj,
    tag: 'view-1',
    dataKey: 'one',
    selector: '.box-1'
  })

  dataHijack({
    data: dataObj,
    tag: 'view-2',
    dataKey: 'two',
    selector: '.box-2'
  })

  dataObj.one = "张三丰"
  dataObj.two = "李四"
</script>
</html>